// list.js
var that;

Page({
    data: {
        page_index: 0,
        orderList: [],
        loadingTip: '上拉加载更多'
    },
    onLoad: function () {
        that = this;
    },
    showDetail: function (e) {
        var index = e.currentTarget.dataset.index;
        // 传递订单索引
        wx.navigateTo({
            url: '../detail/detail?index=' + index
        });
    },
    onShow: function () {
        that.loadOrder();
    },
    loadOrder: function () {
        var page_size = 10;
        var allOrders = wx.getStorageSync('orderList') || [];
        var currentOrders = allOrders.slice(that.data.page_index * page_size, (that.data.page_index + 1) * page_size);

        // 判断是否还有更多内容
        if (currentOrders.length < page_size) {
            that.setData({
                loadingTip: '没有更多内容'
            });
        }

        // 合并当前页面数据与新加载的数据
        that.setData({
            orderList: that.data.orderList.concat(currentOrders)
        });
    },
    onReachBottom: function () {
        that.setData({
            page_index: that.data.page_index + 1
        });
        that.loadOrder();
    },
    payment: function (e) {
        var index = e.currentTarget.dataset.index;
        var order = that.data.orderList[index];
        getApp().payment(order);
    },
    deleteOrder: function (e) {
        var index = e.currentTarget.dataset.index;
        var orderList = that.data.orderList;
        
        wx.showModal({
            title: '提示',
            content: '确定要删除这个订单吗？',
            success: function (res) {
                if (res.confirm) {
                    // 删除订单
                    orderList.splice(index, 1);
                    that.setData({
                        orderList: orderList
                    });
                    // 更新本地存储
                    wx.setStorageSync('orderList', orderList);
                    wx.showToast({
                        title: '订单删除成功',
                        icon: 'success',
                        duration: 2000
                    });
                }
            }
        });
    }
});
